package com.lance.answer.question_export;


import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.Constant;
import com.lance.answer.util.HttpUtil;
import com.lance.answer.util.XinJiangUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 05-14 测试保存视频
 */
public class BatchGetGkQuestionAndAnswerByStudent2 {


    private static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                });
    }

    private static WebElement findWeElement(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<WebElement>)
                d -> {
                    assert d != null;
                    return d.findElement(By.cssSelector(cssSelector));
                });
    }


    /**
     * 查看作答记录
     */
    private static List<WebElement> findTestingRecords(WebDriver driver) {
        // v-btn__content
        List<WebElement> list = Lists.newArrayList();
//        for(WebElement we: (new WebDriverWait(driver, Duration.ofSeconds(20))).until((ExpectedCondition<List<WebElement>>)
//                d -> d.findElements(By.cssSelector("div[class='v-btn__content']")))){
        for (WebElement we : findWeElements(driver, "div[class='v-btn__content'", 30)) {
            if ("查看作答记录".equals(we.getText())) {
                list.add(we);
            }
        }
        return list;
    }

    public static void main(String[] args) throws Exception {

        int sync = 10;
        start(sync);

    }

    public static void start(int sync) throws Exception {

        InputStream inputStream2 = new FileInputStream("d:\\user2020.txt");
        List<String> users = IOUtils.readLines(inputStream2, "utf-8");
      //  List<String> users =  Lists.newArrayList("622301198309189179");

        List<List<String>> group = new ArrayList<>();
        int size = users.size();
        int step = size / sync;
        if (step == 0) {
            group.add(users);
        } else {
            for (int i = 0; i < sync; i++) {
                List<String> list2 = users.subList(step * i, (i + 1) * step);
                group.add(list2);
            }
            group.add(users.subList(step * sync, users.size()));
        }
        for (List<String> batchUser : group) {
            Constant.THREAD_POOL_BATCH.execute(() -> {
                for (String user : batchUser) {
                    if (Strings.isNullOrEmpty(user)) {
                        continue;
                    }
                    String pwd;
                    if (user.contains("x") || user.contains("X")) {
                        pwd = user.substring(11, 17);
                    } else {
                        pwd = user.substring(12);
                    }
                    try {
                        run(user, pwd);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

        }


    }

    public static Set<String> names = Sets.newHashSet();

    static {
        for(File file:new File("D:\\xinjiang4").listFiles()){
            String fileName = file.getName();
            fileName = fileName.substring(0,fileName.length()-5);
            System.err.println("fileName:"+fileName);
            names.add(fileName);
        }
    }

    public static void run(String username, String pwd) throws Exception {
        WebDriver driver = Util.getDriver("c:\\ynouAutoStudy\\chromedriver.exe");
        String url = "https://xjskk.open.com.cn/stuspace-auth/#/login";
        // 打开指定的网站
        driver.get(url);
        Thread.sleep(200);
        try {
            XinJiangUtil.studentLogin(driver, username, pwd);
            Thread.sleep(5000);
            for (WebElement we : findWeElements(driver, "div[class='v-list__tile__title']", 20)) {
                System.err.println("we.getText():" + we.getText());
                if ("我的考试".equals(we.getText())) {
                    we.click();
                    break;
                }
            }
            Thread.sleep(5000);
            List<WebElement> testingRecords = findTestingRecords(driver);
            System.out.println("testingRecordsSize:"+testingRecords.size());
            for (int i = 0; i < testingRecords.size(); i++) {
                Thread.sleep(8000);
                List<WebElement> testingRecords2 = findTestingRecords(driver);
                WebElement testingRecord = testingRecords2.get(i);
                testingRecord.click();
                Thread.sleep(2000);
                // el-table__row
                WebElement table = findWeElement(driver, "tr[class='el-table__row']", 20);
                // 点击查看
                table.findElement(By.tagName("a")).click();
                // TODO 获取信息
                Thread.sleep(5000);
                String name = driver.findElement(By.tagName("h2")).getText();
                System.out.println("courseName:"+name);
//                if (names.contains(name)) {
//                    continue;
//                }
                String text = driver.findElement(By.className("exam-key-class3")).getText();
                text = text.replaceAll("\n","");
                String score = text.substring(4,text.length()-1);
//                if(Integer.parseInt(score)!=100){
//                    continue;
//                }
                String suffix = "&"+username+"&"+score;
                if (names.contains(name+suffix+".json")) {
                    continue;
                }
                names.add(name+suffix+".json");
                System.err.println("text:"+text);
                getResult(driver, name,suffix);
                names.add(name);
                // exam-title-i iconfont icon-arrow-left-circle 返回 FIXME
                driver.findElement(By.cssSelector("i[class='exam-title-i iconfont icon-arrow-left-circle']")).click();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Thread.sleep(5000);
            driver.close();
            driver.quit();
        }
    }

    public static void getResult(WebDriver driver, String courseName,String suffix) throws Exception {
        // https://xjskk.open.com.cn/stuspace/#/doExam-history?courseId=27983&homeworkAnswerId=17331695&pageFrom=allCourseExamList
        String currentUrl = driver.getCurrentUrl();
        currentUrl = currentUrl.substring(currentUrl.indexOf("AnswerId=") + 9);
        Thread.sleep(2000);
        String answerId = currentUrl.substring(0, currentUrl.indexOf("&"));
        String getUrl = "https://xjskk.open.com.cn/api/student/student-space-service/examineAnswer/getHistoryDetail?answerId=" + answerId;
        System.err.println("getUrl:" + getUrl);

        Set<Cookie> cookies = driver.manage().getCookies();
        String studentSpaceProfile = XinJiangUtil.getStudentSpaceProfile(cookies);
        String authorization = XinJiangUtil.getAuthorization(cookies);
        System.err.println("studentSpaceProfile:" + studentSpaceProfile);
        System.err.println("authorization:" + authorization);
        String cookie = Util.getCookie(cookies);
        // 初始化头部
        System.out.println("authorization:" + authorization);
        System.out.println("studentSpaceProfile:" + studentSpaceProfile);
        Map<String, String> heads = XinJiangUtil.initStudentHttpHeads(studentSpaceProfile, authorization);

        String result = HttpUtil.get(getUrl, cookie, heads);
        System.out.println("resultresult:" + result);

        String rootPath = "d://xinjiang3//" + courseName + "//";
//        FileUtils.write(new File(rootPath + answerId + ".json"), result, "utf-8");
//        FileUtils.write(new File("d://xinjiang4//" + answerId + ".json"), result, "utf-8");

        FileUtils.write(new File(rootPath + answerId + ".json"), result, "utf-8");
        FileUtils.write(new File("d://xinjiang4//" + courseName +suffix+ ".json"), result, "utf-8");
        if(courseName.contains("-")){
            courseName = courseName.substring(0,courseName.lastIndexOf("-"));
        }
        FileUtils.write(new File("d://xinjiang5//" + courseName +"//"+suffix+ ".json"), result, "utf-8");


    }


}
